<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\RoomAction;
use App\Admin\Repositories\Room;
use app\model\RoomModel;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class RoomController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Room('user'), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('create_time')->sortable();
            $grid->column('update_time')->sortable();

//            $grid->user()->pluck('login_name')->label();

            // 也可以通过这种方式添加
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new roomAction(User::class));
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Room('user'), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->user(function ($model) {
                $grid = new Grid(new user);
                $grid->model()->join('room_user', function ($join) use ($model) {
                    $join->on('room_user.user_id', 'user.id')
                        ->where('room_id', '=', $model->id);
                })->select('user_id as id', 'login_name');

                // 设置路由
                $grid->setResource('/im/user/');
                $grid->id;

                $grid->login_name;

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->like('login_name')->width('300px');
                });

                return $grid;
            });

            $show->field('create_time');
            $show->field('update_time');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $repository = new Room(['user']);
        return Form::make($repository, function (Form $form) {
            $form->display('id');
            $form->text('name');
            $form->display('update_time');
            $form->submitted(
                function ($form) {
                    if ( $form->isCreating() ) {
                        $form->create_time = time();
                    }
                    $form->update_time = time();
                }
            );
            $form->saved(function (Form $form) {

                return $form
                    ->response()
                    ->success(trans('admin.update_succeeded'))
                    ->redirect('im/room');
            });


        });
    }
}
